import React, { useEffect, useRef, useState } from 'react';
import produce from 'immer';
import './index.less';
import emptyPic from '../../static/image/emptyPic.png';
import ComponentTree from '../componentTree';
import ComponentList from '../componentList';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

// todo: 拖拽过程中鼠标样式问题  拖拽快照偶尔会出现

interface LayoutLeftState {
    clientHeight?: number;
    upHeight?: number;
    downHeight?: number;
}

const minDownHeight = 50;

export default function LayoutLeft() {
    const layoutLeftRef = useRef<HTMLDivElement>();
    const downRef = useRef<HTMLDivElement>();
    const [layoutData, setLayoutData] = useState<LayoutLeftState>({})

    const onMouseMove = (e) => {
        const nextState = produce(layoutData, draft => {
            const upHeight = e.clientY - 40;
            const downHeight = layoutData.clientHeight - upHeight;
            if (downHeight >= minDownHeight) {
                draft.upHeight = upHeight;
                draft.downHeight = downHeight;
            }
        })
        setLayoutData(nextState);
    }

    const onMouseUp = () => {
        document.removeEventListener('mousemove', onMouseMove)
        document.removeEventListener('mouseup', onMouseUp)
    }

    const onMouseDown = (e) => {
        document.addEventListener('mousemove', onMouseMove)
        document.addEventListener('mouseup', onMouseUp)
    }

    

    useEffect(() => {
        const initLayout = () => {
            const nextState = produce(layoutData, draft => {
                draft.clientHeight = layoutLeftRef.current.clientHeight;
                // draft.downHeight最大值不能超过clientHeight容器高度
                draft.downHeight = draft.clientHeight > downRef.current.clientHeight ? downRef.current.clientHeight : draft.clientHeight;
                draft.upHeight = draft.clientHeight - draft.downHeight;
            })
            setLayoutData(nextState);
        }
        window.onresize = initLayout;
        initLayout();

        return () => window.onresize = null;
    }, [])

    return <DndProvider backend={HTML5Backend}>
        <div className='layout-left' ref={layoutLeftRef}>
            <div className="layout-left-up" style={{height: layoutData.upHeight}}>
                <ComponentList />
            </div>
            <div className="layout-left-down" ref={downRef} style={{height: layoutData.downHeight}}>
                <div><div className='row-resize' onMouseDown={onMouseDown}></div>
                </div>
                <div className='down-container'>
                    <ComponentTree />
                </div>
            </div>
        </div>
    </DndProvider>
}